﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SMSSendReceiveTool
{
    class PDUencoding
    {

       
        //对整个要发送的短信的PDU编码
        public string PDUEncodingSMS(string cscaNumber, string PhoneNumber, string TargetText)
        {
            if (!(cscaNumber.Substring(0, 2) == "86"))
            {
                cscaNumber = String.Format("86{0}", cscaNumber);     //检查手机号是否按标准格式书写，不是，就补上“86”
            }
            if (!(PhoneNumber.Substring(0, 2) == "86"))
            {
                PhoneNumber = String.Format("86{0}", PhoneNumber);     //检查手机号是否按标准格式书写，不是，就补上“86”
            }
            //开始号码
            StringBuilder _sb = new StringBuilder();
            _sb.Append("0891");
            //短信中心
            _sb.Append(ReversalNumber(cscaNumber));
            _sb.Append("1100" + String.Format("{0,2:X}", PhoneNumber.Length).Replace(' ', '0') + "91");
            //目标号码
            _sb.Append(ReversalNumber(PhoneNumber));
            //协议标识，编码信息和有效期
            _sb.Append("0008FF");//+ String.Format("{0,2:X}", TargetText.Length * 2).Replace(' ', '0'));
            //短信长度和内容
            _sb.Append(contendEncoding(TargetText));
            return _sb.ToString();
        }
        //短信内容的编码
        public string contendEncoding(string srvContent)
        {
            Encoding encodingUTF = System.Text.Encoding.BigEndianUnicode;
            string s = string.Empty;
            byte[] encodedBytes = encodingUTF.GetBytes(srvContent);
            for (int i = 0; i < encodedBytes.Length; i++)
            {
                s += BitConverter.ToString(encodedBytes, i, 1);
            }
            s = String.Format("{0:X2}{1}", s.Length / 2, s);

            return s;
            

        }
        //手机号码的编码

        public string ReversalNumber(string Target)
        {
            string _strResult = string.Empty;
            if (!(Target.Substring(0, 2) == "86"))
            {
                Target = String.Format("86{0}", Target);     //检查手机号是否按标准格式书写，不是，就补上“86”
            }

            char[] _eachnumber = (Target.Length % 2 == 0) ? Convert.ToString(Target).ToCharArray() : Convert.ToString(Target + "F").ToCharArray();
            for (int i = 0; i < _eachnumber.Length - 1; i += 2)
            {
                _strResult += (_eachnumber[i + 1].ToString() + _eachnumber[i].ToString());
            }
            return _strResult;
        }

        //PDU解码，需要修改返回结果，
       /* public string DecodingSMS(string SourceCode)
        {

            string fromNum = string.Empty;
            string time = "20";
            string Contents = string.Empty;
            //_smsreturn.Tag = 2;
            string _str = SourceCode.Substring(24);
            //解析出号码
            //int num_long =(Int16.Parse( _str.Substring(2,2)));
            char[] _cfrom = _str.Substring(0, _str.IndexOf("0008")).ToCharArray();
            for (int i = 0; i < _cfrom.Length; i += 2)
            {
                fromNum += _cfrom[i + 1].ToString() + _cfrom[i].ToString();
            }
            //解析出时间
            char[] timetoreceive = _str.Substring(fromNum.Length+4, 12).ToCharArray();
            for (int i = 0; i < 6; i += 2)
            {
                time += timetoreceive[i + 1].ToString() + timetoreceive[i].ToString()+"-";
            }
            time = time.Substring(0,time.LastIndexOf("-")) + " ";
            for (int i = 6; i < 12; i += 2)
            {
                time += timetoreceive[i + 1].ToString() + timetoreceive[i].ToString() + ":";
            }
            time = time.Substring(0,time.LastIndexOf(":"));

            _str = _str.Substring(fromNum.Length + 20);
            fromNum = fromNum.Replace("F", "");//去掉F
            while (_str != string.Empty)
            {
               // Encoding.UTF8.GetBytes(((char)Int32.Parse(_str.Substring(0, 4), System.Globalization.NumberStyles.AllowHexSpecifier)).ToString());
                
                Contents += ((char)Int32.Parse(_str.Substring(0, 4), System.Globalization.NumberStyles.AllowHexSpecifier)).ToString();
                _str = _str.Substring(4);
            }
            return fromNum + "\r\n"+time+"\r\n" + Contents;
        }*/
        //重写解码函数
        public string DecodingSMS(string SourceCode)
        {
            List<byte> bytelist = new List<byte>();
            
            string fromNum = string.Empty;
            string time = "20";
            string TP_DCS = string.Empty;//消息编码格式
            
            string Contents = string.Empty;
            
            string _str1 = SourceCode.Substring(20);
            
            //解析出号码
            int num_length = Int32.Parse(_str1.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            if (num_length % 2 != 0) num_length = num_length + 1;
            TP_DCS = _str1.Substring(num_length + 6, 2);

            char[] _cfrom = _str1.Substring(4, num_length).ToCharArray();
            for (int i = 0; i < _cfrom.Length; i += 2)
            {
                fromNum += _cfrom[i + 1].ToString() + _cfrom[i].ToString();
            }
            //解析出时间
            char[] timetoreceive = _str1.Substring(fromNum.Length + 8, 12).ToCharArray();
            for (int i = 0; i < 6; i += 2)
            {
                time += timetoreceive[i + 1].ToString() + timetoreceive[i].ToString() + "-";
            }
            time = time.Substring(0, time.LastIndexOf("-")) + " ";
            for (int i = 6; i < 12; i += 2)
            {
                time += timetoreceive[i + 1].ToString() + timetoreceive[i].ToString() + ":";
            }
            time = time.Substring(0, time.LastIndexOf(":"));

            _str1 = _str1.Substring(fromNum.Length + 24);
            fromNum = fromNum.Replace("F", "");//去掉F
            if(TP_DCS.Equals("08"))
            {
                while (_str1 != string.Empty)
                {

                    Contents += ((char)Int32.Parse(_str1.Substring(0, 4), System.Globalization.NumberStyles.AllowHexSpecifier)).ToString();
                    _str1 = _str1.Substring(4);
                    
                }
            }
            else if(TP_DCS.Equals("04"))
            {
                while (_str1 != string.Empty)
                {
                    byte _sbyte = Byte.Parse(_str1.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
                   
                    
                    bytelist.Add(_sbyte);

                    _str1 = _str1.Substring(2);
                }
                byte [] bytecontest = new byte[bytelist.Count];
                
                    bytecontest = bytelist.ToArray();

                    Contents = Encoding.UTF8.GetString(bytecontest);
                    Contents = Contents.Replace("\0", "");
                

                
            }
            else Contents ="未知编码格式";
            return fromNum + "@@" + time + "@@" + Contents;
        }

        //计算消息长度
        public string CountSMSLength(string PhoneNumber, string TargetText)
        {
            if (!(PhoneNumber.Substring(0, 2) == "86"))
            {
                PhoneNumber = String.Format("86{0}", PhoneNumber);     //检查手机号是否按标准格式书写，不是，就补上“86”
            }
            return (8 + ((PhoneNumber.Length % 2) == 0 ? PhoneNumber.Length / 2 : (PhoneNumber.Length + 1) / 2) + TargetText.Length * 2).ToString();
        }

        
        
    }
}
